package thread.reentranLock;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentranReadWriteTest {

    public static void main(String[] args) {

        ReentranReadWriteService service = new ReentranReadWriteService();
        ThreadReentranWrite tw1 = new ThreadReentranWrite(service);
        ThreadReentranWrite tw2 = new ThreadReentranWrite(service);

        tw1.start();
        tw2.start();


        ThreadReentranRead tr1 = new ThreadReentranRead(service);
        ThreadReentranRead tr2 = new ThreadReentranRead(service);



        tr1.start();
        tr2.start();



    }


}


class ThreadReentranRead extends Thread {
    private ReentranReadWriteService reentranReadWriteService;

    public ThreadReentranRead(ReentranReadWriteService reentranReadWriteService) {
        this.reentranReadWriteService = reentranReadWriteService;
    }

    @Override
    public void run() {
        while (true) {
            reentranReadWriteService.readI();
        }
    }
}


class ThreadReentranWrite extends Thread {
    private ReentranReadWriteService reentranReadWriteService;

    public ThreadReentranWrite(ReentranReadWriteService reentranReadWriteService) {
        this.reentranReadWriteService = reentranReadWriteService;
    }

    @Override
    public void run() {
        while (true) {
            reentranReadWriteService.wirteI();
        }
    }
}

class ReentranReadWriteService {

    //读写锁实验的结果中，写锁更容易获得，因此这里设置为公平锁。
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);

//    AtomicInteger i = new AtomicInteger(0);
    int i =0;

    public void readI() {

        lock.readLock().lock();
        try {

            System.out.println(Thread.currentThread().getName() + "，00000获取读锁00000》》》》》" + i);
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName() + "，00000释放读锁00000---------");
            lock.readLock().unlock();
        }

    }

    public void wirteI() {

        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "，XXXXX获取写锁XXXXX》》》》》" + ++i);
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName() + "，XXXXX释放写锁XXXXX-----------" );
            lock.writeLock().unlock();
        }
    }


}
